/* eslint-disable */
import * as Request from '@/api/liubike';
import { config } from "@/api/config"
import { Toast, Dialog, Swiper, SwiperItem, Icon, Popup } from "mand-mobile";
import store from "@/tools/factory"
import { TMap } from "../../tools/Tmap";
let that = null;
let polling = null; // 轮询订单
let pollingCount = 0; // 最大轮询次数
let isRequest = true

export default {
    components: {
        [Dialog.name]: Dialog,
        [Swiper.name]: Swiper,
        [SwiperItem.name]: SwiperItem,
        [Popup.name]: Popup,
    },
    data() {
        return {
            isTips: true,
            ruleHidden: true,
            showCancel: false,
            autoplay: false,
            interval: 2000,
            isTips: true,
            indicatorDots: true,
            payCode: "",
            duration: 500,
            chooseCard: true,
            check: "WALLET",
            useDirectly: true,
            orderDetail: [],
            promoDetail: [],
            list: [],
            payAmount: 0,
            methods: [],
            hideMethods: [],
            totalAmount: 0,
            payOrderNo: null,
            recCoupon: {},
            tipContent: null,
            status: null,
            setUp: false,
            payMethodId: null,
            animation: '',
            animation2: "",
            animationData: null,
            clearcart: false,
            chooseSize: false,
            dialogType: "payPage",
            showHideMethods: false,
            payStatus: false,
            recommend: true,
            rechargeStatus: false,
            pageSource: "RIDING_END",
            payConfirm: false,
            isActive: false,
            extraBuy: {},
            advertisementType: {}
        }
    },
    mounted() {
        that = this;
        store.set("parkPay", "show");
        if (store.get("couponParams")) {
            this.recommend = false;
            this.rechargeStatus = false
        } else {
            this.recommend = true;
            this.rechargeStatus = false
        }
        if (isRequest) {
            that.getDetail()
        }
    },
    destroyed() {
        isRequest = true;
        store.remove("couponParams");
        store.remove("payOrderNo");
        clearInterval(polling)
    },
    methods: {
        getPayOrderNo(fn) {

        },
        ruleDialogShow() {
            console.log("1111")
        },
        goRecharge() {
            this.$router.push({
                name: "recharge",
                query: {
                    status: 1,
                    source: "payOrder"
                }
            })
        },
        checkPayType(data) { //支付方式选择
            console.log(data)
            if (!data.enabled) {
                return false
            }
            this.check = data.code;
            this.payMethodId = data.payMethodId + "";
            this.useDirectly = data.useDirectly;
        },
        getMethods(fn) { //获取支付方式fgetMethods
            let normalList = [];
            let hideList = [];
            Request.getPayMethods({
                payOrderNo: this.payOrderNo || store.get("payOrderNo")
            }).then(res => {
                Toast.hide();
                if (res.success) {
                    let req = res.data;
                    req.map(item => {
                        if (item.isChecked) {
                            that.check = item.code;
                            that.payMethodId = item.payMethodId;
                            that.useDirectly = item.useDirectly
                        }
                        if (item.isVisible) {
                            normalList.push(item)
                        } else {
                            hideList.push(item)
                        }
                    })
                    that.methods = normalList;
                    console.log("normalList", that.methods)
                    that.hideMethods = hideList;
                    fn && fn()
                }
            }).catch(err => {
                Toast.hide()
            })
        },
        showHideList() {
            let list = [];
            list = [...that.methods, ...that.hideMethods]
            this.methods = list;
            this.hideMethods = []
        },
        getPayStatus(mandatoryCheck) {
            Request.getPayStatus({
                payOrderNo: this.payOrderNo || store.get("payOrderNo"),
                mandatoryCheck: mandatoryCheck || false
            }).then(res => {
                if (res.success) {
                    clearInterval(polling);
                    pollingCount = 0;
                    that.goResultPage()
                }
            })
        },
        goResultPage() {
            store.remove("couponParams");
            that.chooseSize = false;
            if (store.get("pageSource") == "ARREARS_PAY") {
                Dialog.alert({
                    title: '温馨提示',
                    content: "支付成功",
                    confirmText: '确定',
                    onConfirm: function () {
                        that.$router.back(-1)
                    }
                })
            } else {
                that.$router.replace({
                    name: "bill",
                    query: {
                        orderNo: store.get("orderInfo").orderNo
                    }
                })
            }
        },
        hideModal() {
            this.chooseSize = false;
            this.setUp = false
        },
        select(item, index) {
            console.log(item);
            console.log(index)
            let list = that.list;
            if (list[index].select) {
                list[index].select = false;
            } else {
                list.map(item => {
                    item.select = false
                })
                list[index].select = true;
            }
            that.list = list;
            if (list[index].select === true) {
                that.extraBuy = {
                    advertisementType: that.advertisementType,
                    extraBuyAmount: item.price,
                    extraBuyId: item.id
                }
                store.remove("couponParams")
            } else {
                that.extraBuy = {}
            }
            that.getDetail();
        },
        searchResult(mandatoryCheck) {
            if (that.dialogType != "waitPage") {
                this.dialogType = "waitPage"
            }
            polling = setInterval(() => {
                if (pollingCount > 10) {
                    clearInterval(polling);
                    pollingCount = 0;
                    that.dialogType = "failPage"
                    return false;
                }
                that.getPayStatus(mandatoryCheck || false);
                pollingCount += 1; //每刷新一次 pollingCount 就+1
            }, 1000);
        },
        cashierPay() {
            that.cashierPay_parameter()
        },
        cashierPay_parameter() { //收银台支付
            console.log("22222")
            if (this.payStatus) {
                return false
            }
            this.payStatus = true
            let payOrderNo = "";
            if (!that.payOrderNo) {
                payOrderNo = store.get("payOrderNo")
            } else {
                payOrderNo = this.payOrderNo
            }
            Request.cashierPay({
                payMethodId: this.payMethodId,
                payOrderNo: payOrderNo,
                payConfirm: this.payConfirm || false
            }).then(res => {
                Toast.hide()
                that.payStatus = false;
                if (res.success) {
                    let req = res.data;
                    if (!req.syncPay) {
                        if (!req.sdkPay) {
                            //微信免密
                            that.searchResult();
                        } else {
                            // 微信支付
                            that.wxPay(req.sdkPay);
                        }
                    } else {
                        //钱包
                        that.goResultPage()
                    }
                } else {
                    that.chooseSize = false;
                    that.setUp = false
                    if (res.errData && res.errData.errCode == "E2060013") {
                        Dialog.alert({
                            title: '温馨提示',
                            content: res.msg,
                            confirmText: '确定',
                            onConfirm: function () {
                                that.payConfirm = true
                                that.cashierPay_parameter()
                            }
                        })
                        return false
                    }
                    Dialog.alert({
                        title: '温馨提示',
                        content: res.msg,
                        confirmText: '确定',
                        onConfirm: function () {
                            if (res.errData && res.errData.errCode == "E2060003") {
                                that.$router.back(-1)
                            }
                        }
                    })
                }
            }).catch(err => {
                that.payStatus = false
            })
        },
        setUpCashier() {
            that.chooseSize = true;
            if (that.setUp) {
                return false
            }
            that.setUp = true;
            that.dialogType = "payPage";
            Toast.loading("加载中...")
            let pageSource = store.get("pageSource");
            let ridingOrderNo = store.get("orderInfo").orderNo || "";
            let requestData = {
                ridingOrderNo: ridingOrderNo,
                settlementSource: pageSource,
                payConfirm: this.payConfirm
            };
            if (this.recCoupon) {
                requestData = {
                    ridingOrderNo: ridingOrderNo,
                    settlementSource: pageSource,
                    couponId: this.recCoupon.id,
                    couponType: this.recCoupon.couponType.code,
                    payConfirm: this.payConfirm
                }
            }
            if (Object.keys(this.extraBuy).length != 0) {
                let extraBuy = this.extraBuy;
                requestData.extraBuys = [{
                    advertisementType: extraBuy.advertisementType,
                    extraBuyAmount: extraBuy.extraBuyAmount,
                    extraBuyId: extraBuy.extraBuyId
                }]
            }
            Request.payOrder(requestData).then(res => {
                Toast.hide();
                if (res.success) {
                    that.payOrderNo = res.data.payOrderNo || "";
                    store.set("payOrderNo", res.data.payOrderNo);
                    if (res.data.walletQuickPay) {
                        that.payMethodId = 1
                        Toast.loading("正在支付...")
                        that.cashierPay()
                        return false
                    }
                    if (res.data.quickPayMethodId) {
                        that.payMethodId = res.data.quickPayMethodId;
                        that.chooseSize = true;
                        that.dialogType = "waitPage"
                        that.cashierPay()
                        return false
                    }
                    that.getMethods(function () {
                        that.chooseSize = true
                    })
                } else {
                    that.setUp = false
                    if (res.errData && res.errData.errCode == "E2060013") {
                        that.setUp = false;
                        that.chooseSize = true;
                        that.dialogType = "failPage"
                        return false
                    }
                    Dialog.alert({
                        title: '温馨提示',
                        content: res.msg || "没有订单",
                        confirmText: '确定',
                        onConfirm: function () {
                            let errData = res.errData;
                            that.payError(errData)
                        }
                    })
                }
            }).catch(err => {
                Toast.hide()
                this.setUp = false
            })
        },
        payError(errData) {
            if (!errData) {
                return false
            }
            if (errData && errData.errCode == "E2050027") {
                return false
            }
            if ((errData && errData.errCode == "E2050029") || (errData && errData.errCode == "E2050030")) {
                store.remove("couponParams");
                this.extraBuy = {}
                that.getDetail()
                return false
            }
            this.$router.back(-1)
        },
        upCashier() {
            that.setUpCashier()
        },
        goDiscount() {

        },
        getRecommendRidePackage(orderNo) {
            Request.getRecommendRidePackage({
                orderNo: orderNo
            }).then(res => {
                if (res.success && res.data) {
                    let list = res.data.ridePackages;
                    if (!list || list.length == 0) {
                        return false
                    }
                    list.map(item => {
                        item.select = false;
                    })
                    that.list = list;
                    that.advertisementType = res.data.advertisementType;
                }
            })
        },
        getDetail() {
            Toast.loading("订单加载中...")
            let requestData = {};
            let pageSource = store.get("pageSource");
            this.pageSource = pageSource;
            let orderNo = store.get('orderInfo').orderNo || "";
            if (!orderNo) {
                pageSource = "ARREARS_PAY";
                store.set("pageSource", "ARREARS_PAY")
            }
            requestData = {
                ridingOrderNo: orderNo,
                settlementSource: pageSource
            }
            if (store.get("couponParams")) {
                let couponParams = store.get("couponParams");
                if (Object.keys(this.extraBuy).length != 0 && couponParams.couponType != "NO_COUPON") {
                    requestData = {
                        ridingOrderNo: orderNo,
                        settlementSource: pageSource
                    }
                } else {
                    requestData = {
                        couponId: couponParams.couponId || "",
                        couponType: couponParams.couponType,
                        ridingOrderNo: orderNo,
                        settlementSource: pageSource
                    }
                }
            }
            if (Object.keys(this.extraBuy).length != 0) {
                let extraBuy = this.extraBuy;
                requestData.extraBuys = [{
                    advertisementType: extraBuy.advertisementType,
                    extraBuyAmount: extraBuy.extraBuyAmount,
                    extraBuyId: extraBuy.extraBuyId
                }]
            }
            Request.getRidingBill(requestData).then(res => {
                Toast.hide()
                if (res.success) {
                    let req = res.data
                    that.orderDetail = req.orderDetail || [];
                    console.log("orderDetail", that.orderDetail)
                    that.promoDetail = req.promoDetail || []
                    console.log("promoDetail", that.promoDetail)
                    that.totalAmount = req.totalAmount
                    that.payAmount = req.payAmount
                    that.recCoupon = req.recCoupon;
                    console.log("recCoupon", that.recCoupon)
                    that.payOrderNo = req.payOrderNo
                    if (req.payOrderNo) {
                        store.set("payOrderNo", res.data.payOrderNo);
                    }
                    if (req.ridingOrderNo) {
                        store.set("billNo", req.ridingOrderNo)
                    }
                    if (!req.recCoupon) {
                        that.setUpCashier()
                    } else {
                        if (req.recCoupon.couponType.code == "DISABLED_COUPON") {
                            that.getRecommendRidePackage(req.ridingOrderNo)
                        }
                    }
                    if (req.payState) {
                        if (req.payState.code == "WAIT_CHOOSE_PAY_METHOD") {
                            that.setUpCashier()
                        }
                        if (req.payState.code == "PAY_RESULT_UNKNOWN") {
                            that.setUp = false;
                            that.chooseSize = true;
                            that.dialogType = "failPage"
                        }
                        if (req.payState.code == "WAIT_PAY_RESULT") {
                            that.chooseSize = true;
                            that.dialogType = "waitPage"
                            that.searchResult();
                        }
                    }
                } else {
                    Dialog.alert({
                        title: '温馨提示',
                        content: res.msg || "没有订单",
                        confirmText: '确定',
                        onConfirm: function () {
                            let errData = res.errData;
                            that.payError(errData)
                        }
                    })
                }
            }).catch(err => {
                Toast.hide()
            })
        },
    }
}